package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public void save(Video video) {
        video.setId(new ObjectId());
        video.setCreated(new Date().getTime());
        Long vid = idService.getNextId("video");
        video.setVid(vid);
        mongoTemplate.save(video);
    }

    @Override
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        Query query = new Query();
        query.limit(pagesize).skip((page-1)*pagesize);
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        return new PageResult(page,pagesize,(int)count,videoList);
    }

    @Override
    public PageResult queryVideoListByUserId(Integer page, Integer pagesize, Long uid) {
        Query query = new Query(Criteria.where("userId").is(uid));
        query.limit(pagesize).skip((page-1)*pagesize);
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        return new PageResult(page,pagesize,(int)count,videoList);
    }
}
